package com.lx.zy.project.common;


import com.lx.zy.common.constant.Constants;
import com.lx.zy.common.utils.IdUtils;
import com.lx.zy.common.utils.VerifyCodeUtils;
import com.lx.zy.common.utils.sign.Base64;
import com.lx.zy.framework.redis.RedisCache;
import com.lx.zy.framework.web.domain.AjaxResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @program: zy-vue
 * @description: 验证码操作处理
 * @author: Lx
 * @create: 2019-10-18 22:15
 **/
@RestController
public class CaptchaController
{
    public static final Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @Autowired
    private RedisCache redisCache;

    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        // logger.debug("请求了captchaImage");
        //随机生成字符串（长度4）
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        //存入redis 2分钟过期
        redisCache.setCacheObject(verifyKey, verifyCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try
        {
            AjaxResult ajaxResult = AjaxResult.success();
            ajaxResult.put("uuid", uuid);
            ajaxResult.put("img", Base64.encode(stream.toByteArray()));
            logger.debug("【uuid】:{}", uuid);
            logger.debug("【key-verifyKey】:{}", redisCache.getCacheObject(verifyKey).toString());
            return ajaxResult;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        finally
        {
            stream.close();
        }
    }

    @GetMapping("/get")
    public String get()
    {
        return "xxxxxxxxxxxxxxxxxxx";
    }
}
